package com.hongawen.callable;

import java.util.concurrent.*;

/**
 * callable启动线程的方式，需要结合线程池
 * 1、实现callable接口，需要返回值类型
 * 2、重写call方法，需要抛出异常
 * 3、创建目标对象
 * 4、创建执行服务：ExecutorService ser = Executors.newFixedThreadPool(1)
 * 5、提交执行：Future<String> result = ser.submit(t1)
 * 6、获取结果：String msg = result.get();
 * 7、关闭服务：ser.shutdownNow();
 *
 * @author hongawen
 * @version 1.0.0
 * @date 2021年08月31日 16:07
 */
public class TestCallable {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CallableThread  callableThread = new CallableThread();
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        Future<String> result = executorService.submit(callableThread);
        for (int i = 0; i < 10; i++) {
            System.out.println("main正在执行线程内容" + i);
        }
        TimeUnit.MINUTES.sleep(1);
        //会阻塞等待callable线程结束
        System.out.println(result.get());
        executorService.shutdown();
    }
}

class CallableThread implements Callable<String> {


    @Override
    public String call() throws Exception {

        for (int i = 0; i < 10; i++) {
            System.out.println("正在执行线程内容" + i);
        }

        return "hello";
    }
}
